<?

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');
include($_SERVER['DOCUMENT_ROOT'].'/filter.libs.php');

$bits = explode('.',$_SERVER['SERVER_NAME']);
$domain = $bits[0];

$row = getRow("SELECT portal_id,title,user_id,realname,readable FROM portal INNER JOIN user USING (user_id) WHERE domain = ".dbQuote($domain)." AND status_id = 1");

if (empty($row['portal_id'])) {
	header("HTTP/1.0 404 Not Found");
	print "<html><head>";
	print "<title>Not found!</title>";
	print "</head><body>";
	print "<p>The page you are looking for is not available</p>";
	
	print "<p><a href=\"http://www.geographs.org/portals/?ref=$domain\">Try the Portal Homepage</a></p>";
	print "</body></html>";
	print str_repeat(" ",500);
	exit;
}

$portal_id = $id = intval($row['portal_id']);
$title = $row['title'];

$row['count'] = count_active($id);

$page_title = "Breakdown";
include($_SERVER['DOCUMENT_ROOT'].'/header.inc.php');


#########################
# Setup Defaults


$sql = array();
$sql['columns'] = 'SUBSTRING(imagetaken,1,4) AS name,COUNT(*) AS count';
$sql['tables'] = array();

$sql['tables'][] = "p2.gridimage{$id}_bi_view AS gi";


$sql['wheres'] = array();

$sql['group'] = "SUBSTRING(imagetaken,1,4)";
$sql['limit'] = 100;

#########################
# Possiblities and defaults

$view = 'text';
$by = 'year';
$bytitle = "Year Taken";
$filter = 'taken';
$pgsize = $sql['limit'];
$order = 'name';


$views = array(
'text' => '&middot; Text Listing',
'cloud' => '&middot; Word Cloud',
);

$bys = array(
'year' => 'Year Taken',
'yearmonth' => 'Year+Month Taken',
'month' => 'Month Taken',
'realname' => 'Contributor Name',
'user_id' => 'Contributor ID',
'category' => 'Category',
'canonical' => 'Canonical Category',
'mod' => 'Classification',
'myriad' => 'Myriad',
'hectad' => 'Hectad',
'cluster' => 'Automatic Cluster',
'cluster2' => 'Automatic Cluster2',
'term' => 'Terms',
'tag' => 'Tags',
##'gridref' => 'Grid Reference',
);

$orders = array(
'name' => 'Name/Title',
'count' => 'Count'
);

#########################
# Customise



if (!empty($_GET['by'])) {
	if ($_GET['by'] == 'user_id' || $_GET['by'] == 'realname') {
		$sql['columns'] = 'realname AS name,user_id AS value,COUNT(*) AS count';
		$sql['group'] = "user_id";
		$filter = "bi_id";
		$by = $_GET['by'];
	} elseif ($_GET['by'] == 'year') {
		$sql['columns'] = 'SUBSTRING(imagetaken,1,4) AS name,COUNT(*) AS count';
		$sql['group'] = "SUBSTRING(imagetaken,1,4)";
		$filter = "taken";
		$by = 'year';
	} elseif ($_GET['by'] == 'month') {
		$sql['columns'] = 'SUBSTRING(imagetaken,6,2) AS name,COUNT(*) AS count';
		$sql['group'] = "SUBSTRING(imagetaken,6,2)";
		$filter = "taken";
		$by = 'month';
	} elseif ($_GET['by'] == 'yearmonth') {
		$sql['columns'] = 'SUBSTRING(imagetaken,1,7) AS name,COUNT(*) AS count';
		$sql['group'] = "SUBSTRING(imagetaken,1,7)";
		$filter = "taken";
		$by = 'yearmonth';
	} elseif ($_GET['by'] == 'taken') {
		$sql['columns'] = 'imagetaken AS name,COUNT(*) AS count';
		$sql['group'] = "imagetaken";
		$filter = "taken";
		$by = 'taken';
	} elseif ($_GET['by'] == 'category') {
		$sql['columns'] = 'imageclass AS name,COUNT(*) AS count';
		$sql['group'] = "imageclass";
		$filter = "category";
		$by = 'category';
	} elseif ($_GET['by'] == 'canonical') {
		$sql['tables']['cc'] = "INNER JOIN geograph_live.category_canonical AS cc USING (imageclass)";
		$sql['columns'] = 'canonical AS name,COUNT(*) AS count';
		$sql['group'] = "canonical";
		$filter = "canonical";
		$by = 'canonical';
	} elseif ($_GET['by'] == 'mod') {
		$sql['columns'] = 'moderation_status AS name,COUNT(*) AS count';
		$sql['group'] = "moderation_status";
		$filter = "mod";
		$by = 'mod';
	} elseif ($_GET['by'] == 'ftf') {
		$sql['columns'] = 'ftf AS name,COUNT(*) AS count';
		$sql['group'] = "ftf";
		$filter = "ftf";
		$by = 'ftf';
	} elseif ($_GET['by'] == 'myriad') {
		$sql['group'] = "SUBSTRING(gi.grid_reference,1,3 - reference_index)"; //TODO BI specific!
		$sql['columns'] = $sql['group'].' AS name,COUNT(*) AS count';
		$filter = "myriad";
		$by = 'myriad';
	} elseif ($_GET['by'] == 'hectad') {
		$sql['group'] = "concat(substring(gi.grid_reference,1,length(gi.grid_reference)-3),substring(gi.grid_reference,length(gi.grid_reference)-1,1))"; //TODO BI specific!
		$sql['columns'] = $sql['group'].' AS name,COUNT(*) AS count';
		$filter = "hectad";
		$by = 'hectad';
	} elseif ($_GET['by'] == 'gridref') {
		$sql['columns'] = 'moderation_status AS name,COUNT(*) AS count';
		$sql['group'] = "moderation_status";
		$filter = "gridref";
		$by = 'gridref';
		$bys['gridref'] = 'Grid Reference'; //we dont show it always!
	} elseif ($_GET['by'] == 'shared') {
		$sql['tables'][] = "INNER JOIN geograph_live.gridimage_snippet AS gs USING (gridimage_id)";
		$sql['tables'][] = "INNER JOIN geograph_live.snippet AS s USING (snippet_id)";
		$sql['columns'] = 's.title AS name,COUNT(*) AS count';
		$sql['group'] = "snippet_id";
		$filter = "snippet_id";
		$by = 'shared';
	} elseif ($_GET['by'] == 'cluster') {
		$sql['tables'][] = "INNER JOIN geograph_live.gridimage_group AS gg USING (gridimage_id)";
		$sql['columns'] = 'label AS name,COUNT(*) AS count';
		$sql['group'] = "label";
		$filter = "cluster";
		$by = 'cluster';
	} elseif ($_GET['by'] == 'term') {
		$sql['tables']['gt'] = "INNER JOIN geograph_live.gridimage_term AS gt USING (gridimage_id)";
		$sql['columns'] = 'term AS name,COUNT(*) AS count';
		$sql['group'] = "term";
		$filter = "term";
		$by = 'term';
	} elseif ($_GET['by'] == 'cluster2') {
		$sql['tables'][] = "INNER JOIN gridimage_group AS gg USING (gridimage_id)";
		$sql['wheres'][] = "gg.portal_id = $portal_id";
		$sql['columns'] = 'label AS name,COUNT(*) AS count';
		$sql['group'] = "label";
		$filter = "cluster2";
		$by = 'cluster2';
	} elseif ($_GET['by'] == 'tag') {
		$sql['tables']['gt'] = "INNER JOIN p2.gridimage_tag{$portal_id}_bi_view AS gt USING (gridimage_id)";
		$sql['columns'] = 'gt.display AS name,COUNT(*) AS count';
		$sql['group'] = "tag";
		$filter = "tag";
		$by = 'tag';
	} 
} 

if (!empty($_GET['order'])) {
	if (!empty($_GET['in']) && strlen($_GET['in']) == 1) $in = $_GET['in'];
	$asc = ($in == 'a')?'asc':'desc';
	switch ($_GET['order']) {
		case 'count': $sql['order'] = "`count` $asc"; $order = 'count';break;
		case 'group': 
		     default:  
			if ($_GET['by'] == 'realname') {
				$sql['order'] = "`realname` $asc";
			} elseif ($asc == 'desc') {
				$sql['group'] .= " $asc";
			} 
			$order = 'group'; break;
	}
	$title = '';
}

#if ($sql['order'] == '`count` desc') {
	$views['wordle'] = '&middot; Wordle Maker';
#}

if (!empty($_GET['view'])) {
	
	if (isset($views[$_GET['view']])) {
		$view = $_GET['view'];
	}
} 

#########################
# html form

print "<form class=\"sform\">";

print "<div class=\"d\">";
print "View style<br/>";
print "<select name=\"view\" onchange=\"this.form.submit()\">";
foreach ($views as $key => $value) {
	printf("<option value=\"%s\"%s>%s</option>",$key,($key==$view)?' selected':'',$value);
}
print "</select></div>";

print "<div class=\"d\">";
print "by<br/>";
print "<select name=\"by\" onchange=\"this.form.submit()\">";
foreach ($bys as $key => $value) {
	printf("<option value=\"%s\"%s>%s</option>",$key,($key==$by)?' selected':'',$value);
}
print "</select></div>";

print "<div class=\"d\">";
print "Order<br/>";
print "<select name=\"order\" onchange=\"this.form.submit()\">";
foreach ($orders as $key => $value) {
	printf("<option value=\"%s\"%s>%s</option>",$key,($key==$order)?' selected':'',$value);
}
print "</select>";
print "<select name=\"in\" onchange=\"this.form.submit()\">";
$ins = array('a'=>'Asc','d'=>'Desc');
foreach ($ins as $key => $value) {
	printf("<option value=\"%s\"%s>%s</option>",$key,($key==$in)?' selected':'',$value);
}
print "</select></div>";

print "<br>";

include($_SERVER['DOCUMENT_ROOT'].'/filter_setup.inc.php');

if ($_GET['resort'])
	print "<input type=hidden name=resort value=1 />";

print "</form>";

#########################
# paging

if (!empty($_GET['page'])) {
				
	$page = intval($_GET['page']);

	if (empty($page) || $page < 1) {$page = 1;}
	#if ($page > $numberOfPages) {$page = $numberOfPages;}

	$pg = ($page -1)* $pgsize;

	$sql['limit'] = "$pg,$pgsize";
} else {
	$page = 1;
	$pg = 0;
}

#########################
# Display results!

$query = sqlMakeQuery($sql);
if ($_GET['qq']) 
	print_rp($query);
	
		list($usec, $sec) = explode(' ',microtime());
		$querytime_before = ((float)$usec + (float)$sec);

if ($_GET['resort'])
	$query = "SELECT * FROM ($query) t1 ORDER BY name";

$result = queryExecute($query);

		list($usec, $sec) = explode(' ',microtime());
		$querytime_after = ((float)$usec + (float)$sec);

		if (($querytime_after-$querytime_before) > 0.1) {
			$hh = fopen("./slow.log",'a');
			fprintf($hh,"%0.4f,BREAK,%d,%d,%s\n",$querytime_after-$querytime_before,$portal_id,time(),str_replace(array("\n","\r"),' ',$query));
			fclose($hh);
		}

if ($result) {
	print "<h3>Breakdown by {$bys[$by]} in the ".he($row['title'])." portal</h3>";
	
	if ($_GET['by'] == 'cluster') {
		print "NOTE: Images can be tagged with multiple labels (ie in multiple clusters)";
	} 
	
	if ($by == 'year') {
		print "<p>&middot;<a href=\"/?opt=byyear4&amp;view=thumbs\">View as Thumbnails &gt;&gt;</a></p>";
	} elseif ($by == 'category') {
		print "<p>&middot;<a href=\"/?opt=categories&amp;view=thumbs\">View as Thumbnails &gt;&gt;</a></p>";
	} elseif ($by == 'user_id' || $by == 'realname') {
		print "<p>&middot;<a href=\"/?opt=users&amp;view=thumbs\">View as Thumbnails &gt;&gt;</a></p>";
	}
	switch ($by) {
		case 'shared': print "<p class=banner>The <b>Title</b> shown here are the titles from user contributed Shared Descriptions.</p>"; break;
		case 'tag': print "<p class=banner>The <b>Tag</b> shown here are keywords/short sentances attached to each image. A image can have multiple tags, as can tags be attached to multiple images. In general the are assigned manually by the portal maker, but some portals might have them imported.</p>"; break;
		case 'cluster': print "<p class=banner>The <b>Cluster label</b> shown here is an automatically extracted label for a photo. The analysis (by the <a href=\"http://project.carrot2.org/\">Carrot2</a> software) is done on a grid square basis on the main Geograph site.</p>"; break;
		case 'cluster2': print "<p class=banner>The <b>Cluster2 label</b> shown here is an automatically extracted label for a photo. The analysis (by the <a href=\"http://project.carrot2.org/\">Carrot2</a> software) is done directly in this portal, so tends to work well on the highly specific images (usually better than 'cluster').</p>"; break;
		case 'term': print "<p class=banner>The <b>Term</b> shown here is an automatically extracted label for a photo. The extraction is done with the <a href=\"http://developer.yahoo.com/search/content/V1/termExtraction.html\">Yahoo Term Extraction API</a>. NOTE: only images upto id 1458144 have been analyised.</p>"; break;
	}
	if ($view == 'wordle') {
		
		?>
		<form action="http://www.wordle.net/compose" method="post" name="theForm" style="background-color:silver;padding:20px;"> 
		<input type=text name=wordcounts readonly value="<? 
		while($c = mysql_fetch_assoc($result)) {
			if ($c['name'] != '(Other)')
				print he(str_replace(',',' ',$c['name'])).":{$c['count']},";
		}
		?>"> 
		<input type=submit value="Continue to wordle.net &gt;&gt;"> 
		</form>
		<p>Wordle.net is a cool website, allowing creating of visually appealing 'word clouds' based on word frequencies. This page loads the data you have selected above into the wordle.net composer screen.</p>
		<?
		
		
	} elseif ($view == 'cloud') {
		
		$mult = ($by == 'cluster2')?0.4:0.6;
		
		print "<div class=\"cloud\">";
		while($c = mysql_fetch_assoc($result)) {
			if (empty($c['value'])) {
				$c['value'] = $c['name'];
			}
			$link = linktoself(array($filter=>$c['value'],'delete'=>array('by','order','in')),'/'); 
			$size = sprintf("%.1f",log($c['count']*30))*$mult;
			echo "&middot;<a href=\"$link\" style=\"font-size:{$size}em\" title=\"{$c['count']} image(s)\">".he($c['name'])."</a>&middot; ";

		}
		print "</div>";
		
	} else {
		print "<table class=\"report\">";
		print "<tr>";
		print "<th>{$bys[$by]}</th>";
		print "<th>Count</th>";
		print "</tr>";

		while($c = mysql_fetch_assoc($result)) {
			if (empty($c['value'])) {
				$c['value'] = $c['name'];
			}
			print "<tr>";
			$link = linktoself(array($filter=>$c['value'],'delete'=>array('by','order','in','view')),'/'); 
			print "<td><a href=\"$link\">".he($c['name'])."</a></td>";

			print "<td align=right>{$c['count']}</td>";

			print "</tr>";

		}
		print "</table>";
	}
	
	if (mysql_num_rows($result) == $pgsize || isset($_GET['page'])) {
		$count_query = sqlMakeCountQuery($sql);

		$resultCount = getOne($count_query);

		#if ($resultCount > mysql_num_rows($result)) {
		#	print "Showing $pgsize of $resultCount rows";
		#}

		$numberOfPages = ceil($resultCount/$pgsize);

		if ($numberOfPages > 1) {
			print "<p class='pages'>Page $page of $numberOfPages. ";
			printf("Row %d..%d of %d. ",($pg)+1,min(($pg)+$pgsize,$resultCount),$resultCount);
			print pagesString($page,$numberOfPages)."</p>";
		}

	}
	
	
	if ($filtered) {
		print "<p align=center><a href=\"".linktoself(array('view'=>'thumbs','delete'=>array('by','order','in')),'/')."\">View these images</a></p>";
	}
		
	switch ($by) {
		case 'shared': print "<p class=banner>The <b>Title</b> shown here are the titles from user contributed Shared Descriptions.</p>"; break;
		case 'tag': print "<p class=banner>The <b>Tag</b> shown here are keywords/short sentances attached to each image. A image can have multiple tags, as can tags be attached to multiple images. In general the are assigned manually by the portal maker, but some portals might have them imported.</p>"; break;
		case 'cluster': print "<p class=banner>The <b>Cluster label</b> shown here is an automatically extracted label for a photo. The analysis (by the <a href=\"http://project.carrot2.org/\">Carrot2</a> software) is done on a grid square basis on the main Geograph site.</p>"; break;
		case 'cluster2': print "<p class=banner>The <b>Cluster2 label</b> shown here is an automatically extracted label for a photo. The analysis (by the <a href=\"http://project.carrot2.org/\">Carrot2</a> software) is done directly in this portal, so tends to work well on the highly specific images (usually better than 'cluster').</p>"; break;
		case 'term': print "<p class=banner>The <b>Term</b> shown here is an automatically extracted label for a photo. The extraction is done with the <a href=\"http://developer.yahoo.com/search/content/V1/termExtraction.html\">Yahoo Term Extraction API</a>. NOTE: only images upto id 1458144 have been analyised.</p>"; break;
	}	
} else {
	print "<p>No Images to show at this time.</p>";
}

include($_SERVER['DOCUMENT_ROOT'].'/footer.inc.php');


#########

